import Vue from "vue";
import Router from "uni-simple-router";
import { UIplugins } from "../common/UIplugins";
import { store } from "../store";

Vue.use(Router);

const routes = [
	{
		name: "Index",
    aliasPath:'/',  //对于h5端你必须在首页加上aliasPath并设置为/
		path: "/pages/tabBar/Index"
	},
	{
		name: "Category",
		path: "/pages/tabBar/Category"
	},
	{
		name: "Cart",
		path: "/pages/tabBar/Cart",
    meta:{requireAuth: true }
	},
	{
		name: "User",
		path: "/pages/tabBar/User",
    meta:{requireAuth: true }
	},
	{
		name: "DebugSetting",
		path: "/pages/DebugSetting"
	},
];

// 获取当前文件夹下的js文件列表并加入到routes数组
const files = require.context('.', false, /\.js$/);
files.keys().forEach(key => {
  if(key.indexOf('index') < 0){
    //routes.concat(files(key).default);
    routes.push(...files(key).default);
  }
});

const router = new Router({
	/* encodeURI:false 取消编码传输数据。
		一些特殊符号则被限制，同样深度对象传递时就无法进行传递，他会扁平成一个大对象 
		详细参考: http://hhyang.cn/src/router/start/cross/params.html
	*/
	encodeURI:false,
  routes
});

router.beforeEach((to, from, next) => {
	console.log('from:', from, 'to:', to)
	function requireAuth(){ // 判断是否需要登录验证的页面
		return new Promise(function(resolve, reject) {
			if(to.meta && to.meta.requireAuth) {
				if (store.getters.getToken != '') 
					resolve();
				else 
					reject({
						path: '/pages/login/Login', 
						mess: '未登录 或 登陆信息失效，请重新登陆'
					});
			}else resolve();
		});
	}
	// 开始验证
	requireAuth().then( ()=> {
		next();
	}).catch( (data)=> {
		console.log(data);
		if(data.path == '/pages/login/Login'){
			store.commit('updateToken', '');
			// console.log(store.getters['user/getUserInfo'])
			store.commit('user/updateUserInfo', {});
			UIplugins.message({message: data.mess, type: 'error'});
			next({
				path: data.path,
				query: {redirect: to.path},   //从哪个页面跳转
				NAVTYPE: 'replace' // 在tabBar想导航到新的地址需要在 next() 传递一个 NAVTYPE 指定类型跳转。
			});
		}else next(data.path);
	});
});

export default router;